<!--
 * 群组管理--分配人员
 * @author: hexiaozhen
 * @since: 2023-11-1
 * allocation.vue
-->
<template>
  <a-drawer width="800px" v-model:visible="visibleModal" @ok="handleOk" @cancel="handleCancel" unmountOnClose>
    <template #title> {{ rowData.groupName }}分配人员 </template>
    <div class="main-content">
      <div class="tree margin-r-2">
        <a-input style="margin-bottom: 8px" v-model="searchKey" allow-clear>
          <template #prefix><icon-search /></template>
        </a-input>
        <a-scrollbar class="scroll-container">
          <a-tree
            :data="treeData"
            v-model:expanded-keys="expandedKeys"
            :field-names="{ key: 'deptId', title: 'deptName' }"
            @select="clickNode"
          >
            <template #switcher-icon="node, { expanded }">
              <span
                v-if="Boolean(node.children && node.children.length) && expanded"
                class="iconfont icon-shouqi"
              ></span>
              <span v-else class="iconfont icon-zhankai"></span>
            </template>
            <template #title="nodeData">
              <template v-if="((index = getMatchIndex(nodeData?.deptName)), index < 0)">
                {{ nodeData?.deptName }}
              </template>
              <span v-else>
                {{ nodeData?.deptName?.substr(0, index) }}
                <span style="color: var(--color-primary-light-4)">
                  {{ nodeData?.deptName?.substr(index, searchKey.length) }}
                </span>
                {{ nodeData?.deptName?.substr(index + searchKey.length) }}
              </span>
            </template>
          </a-tree>
        </a-scrollbar>
      </div>
      <div class="table">
        <h3 class="title">待分配人员</h3>
        <TableForm
          ref="tableRef"
          :girdOption="girdOption"
          @getTableList="getTableList"
          @select="tableSelectFn"
          @select-all="selectAll"
        />
      </div>
    </div>
    <h3 class="title">群组成员</h3>
    <TableForm ref="selTableRef" class="tableForm" :girdOption="selGirdOption" />

    <template #footer>
      <footer>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="handleOk">确定</a-button>
      </footer>
    </template>
  </a-drawer>
</template>

<script setup>
import { reactive, ref, onMounted, computed, toRefs } from 'vue'
import TableForm from '@/components/tableForm/index.vue'
import system from '@/api/modules/system'
import { Message } from '@arco-design/web-vue'

const props = defineProps({
  // 表单json配置项
  visible: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
    default: () => {
      return {
        type: '',
      }
    },
  },
})
const { visible, rowData } = toRefs(props)
const emit = defineEmits(['update:visible', 'submit'])
let visibleModal = ref(false) // 弹窗显示与隐藏
visibleModal.value = visible.value
const formData = reactive({ deptId: '' })
const tableRef = ref() // 待选
const selTableRef = ref() // 已选

// 待选区表头
const girdOption = reactive({
  columns: [
    { title: '用户账号', dataIndex: 'userName' },
    { title: '用户姓名', dataIndex: 'nickName' },
  ],
  loading: false,
  tableId: 'userId', //表格唯一标识符类似于id
  pagination: false, // 无分页
  rowSelection: true,
  selectedKeys: [],
})
// 已选区表头
const selGirdOption = reactive({
  columns: [
    { title: '序号', slotName: 'serialNumber', width: 70 },
    { title: '用户账号', dataIndex: 'userName' },
    { title: '用户姓名', dataIndex: 'nickName' },
    { title: '部门', dataIndex: 'deptName' },
  ],
  tableId: 'userId', //表格唯一标识符类似于id
  pagination: false, // 无分页
})

// 确定
const handleOk = () => {
  const tableData = selTableRef.value.getTableData()
  if (!tableData.length) {
    return Message.warning('请先选择数据！')
  }
  let param = {
    userList: tableData.map((item) => {
      return { userId: item.userId, userName: item.userName }
    }),
    groupId: rowData.value.groupId,
    groupCode: rowData.value.groupCode,
  }

  system.assignGroup(rowData.value.groupId, param).then((res) => {
    visibleModal.value = false
    Message.success(res.msg)
    emit('submit')
    emit('update:visible', false)
  })
}
// 取消
const handleCancel = () => {
  visibleModal.value = false
  emit('update:visible', false)
}
// 获取表格数据
const getTableList = () => {
  girdOption.loading = true
  system
    .getUserByDept(formData.deptId)
    .then((res) => {
      tableRef.value.setTableData(res.data)
      girdOption.loading = false
    })
    .catch(() => {
      girdOption.loading = false
    })
}
// 多选
const tableSelectFn = (data) => {
  let selTableData = selTableRef.value.getTableData()
  const findIndex = selTableData.findIndex((it) => {
    return it.userId === data.record.userId
  })
  if (findIndex !== -1) {
    selTableData.splice(findIndex, 1)
  } else {
    selTableData.push(data.record)
  }
  selTableRef.value.setTableData(selTableData)
}
// 全选全不选
const selectAll = (checked) => {
  let tableData = tableRef.value.getTableData()
  let selTableData = selTableRef.value.getTableData()
  for (let i = 0; i < tableData.length; i++) {
    const findIndex = selTableData.findIndex((it) => {
      return it.userId === tableData[i].userId
    })
    if (findIndex !== -1) {
      if (!checked) {
        selTableData.splice(findIndex, 1)
      }
    } else {
      if (checked) {
        selTableData.push(tableData[i])
      }
    }
  }

  selTableRef.value.setTableData(selTableData)
}

// 部门树
const searchKey = ref('')
const originTreeData = ref([])
const expandedKeys = ref([])
const getTree = () => {
  system.getDeptList().then((res) => {
    originTreeData.value = res.data
    if (res.data.length) {
      expandedKeys.value = [res.data[0].deptId]
      formData.deptId = res.data[0].deptId
      getTableList()
    }
  })
}
const treeData = computed(() => {
  if (!searchKey.value) return originTreeData.value
  return searchData(searchKey.value)
})
// 过滤树
const searchData = (keyword) => {
  const loop = (data) => {
    const result = []
    data.forEach((item) => {
      if (item.deptName.toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
        result.push({ ...item })
      } else if (item.children) {
        const filterData = loop(item.children)
        if (filterData.length) {
          result.push({
            ...item,
            children: filterData,
          })
        }
      }
    })
    return result
  }
  return loop(originTreeData.value)
}
// 搜索词匹配
const getMatchIndex = (title) => {
  if (!searchKey.value) return -1
  return title.toLowerCase().indexOf(searchKey.value.toLowerCase())
}
// 点击树
const clickNode = (selectKeys) => {
  formData.deptId = selectKeys[0]
  getTableList()
}
//  数据字典
const getOption = () => {
  system.detailGroup(rowData.value.groupId).then((res) => {
    selTableRef.value.setTableData(res.data.userList)
    let arr = []
    res.data.userList.forEach((it) => {
      arr.push(it.userId)
    })
    girdOption.selectedKeys = arr
  })
}

onMounted(() => {
  // 获取树
  getTree()
  getOption()
})
</script>

<style scoped lang="less">
// @size-21减去标题的高度84px
.tableForm {
  height: calc(50% - @size-21) !important;
}
.main-content {
  height: calc(50%) !important;
  display: flex;
  padding: 0;
}
.tree {
  width: @tree-width;
  background-color: var(--color-bg-2);
  padding: 8px;
  padding-top: 11px;
}
:deep(.tree .arco-scrollbar) {
  height: calc(100% - @size-10) !important;
  .scroll-container {
    height: 100%;
    overflow: auto;
  }
}

// @size-16减去标题的高度64px
.table {
  width: calc(100% - @tree-width);
  height: calc(100% - @size-16) !important;
}

:deep(.arco-card-body) {
  padding: 0;
}
</style>
